package com.hgk.common.common.ui.activity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.common.dongqiuhui.apps.comm.constants.KeysConstans;
import com.common.dongqiuhui.apps.comm.tools.BallUtil;
import com.common.dongqiuhui.apps.comm.util.SharedPreferencesUtil;
import com.hgk.common.common.ui.view.BallWebView;
import com.hgk.wanwan.main.MainActivity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import width.hgk.wanwan.R;
/**
 * 自定义Webview<br>
 * 注:<br>
 * 混淆加-keep class (包名).BabyTreeWebviewActivity$JavaScriptInterface
 */
@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
public class BallWebviewActivity extends BallTitleAcitivty {
	private static final String TAG = BallWebviewActivity.class.getSimpleName();
    public static final String BUNDLE_URL = "url";
    public static final String BUNDLE_TITLE = "title";
    public static final String BUNDLE_PUSH="ispush";
    public static final String BUNDLE_PICURL="tag_pic";
	/**
	 * 网页URL
	 */
	private String mUrl;
    private boolean mPush=false;
	private BallWebView mWebView;
    private String mTitle,mPicUrl;
    private String mPicPath;
    public ProgressBar mProgressBar;

	protected WebView getmWebView() {
		return mWebView;
	}

	public void onCreate(Bundle savedInstanceState) {
        Intent mIntent = getIntent();
        mUrl = mIntent.getStringExtra(BUNDLE_URL);
        mTitle = mIntent.getStringExtra(BUNDLE_TITLE);
        mPush=mIntent.getBooleanExtra(BUNDLE_PUSH, false);
        mPicUrl = mIntent.getStringExtra(BUNDLE_PICURL);
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView(){
        viewTitle.getFramelayout().setVisibility(View.VISIBLE);
        mProgressBar=(ProgressBar)findViewById(R.id.myProgressBar);
        mWebView=(BallWebView)this.findViewById(R.id.webview_play);
        mWebView.loadUrl(mUrl);
    }

    @Override
    public void setLeftButton(RelativeLayout relativeLayout,Button button) {

    }
    @Override
    public void setRightButton(RelativeLayout relativeLayout,Button button) {
//        button.setVisibility(View.VISIBLE);
//        button.setBackground(getResources().getDrawable(R.drawable.icon_share));
//        button.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //TODO  点击此按钮可以实现QQ，微信，微博的的分享操作
//                ImageLoader.getInstance().loadImage(mPicUrl, new ImageLoadingListener() {
//                    @Override
//                    public void onLoadingStarted(String imageUri, View view) {
//
//                    }
//
//                    @Override
//                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
//
//                    }
//
//                    @Override
//                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//                        try {
//                            saveFile(loadedImage, "sharepic");//
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//
//                    @Override
//                    public void onLoadingCancelled(String imageUri, View view) {
//
//                    }
//                });
//            }
//        });
    }

    /**
     * 保存文件（主要功能是：将图片下载并保存到本地，分享时用到）
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public void saveFile(Bitmap bm, String fileName) throws IOException {
        String path = getSDPath() +"/revoeye/";
        File dirFile = new File(path);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        mPicPath = myCaptureFile.getPath();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
//        showShare();
    }
    public static String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    /*private void showShare() {
        ShareSDK.initSDK(mContext);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(mTitle);

        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
       // oks.setTitleUrl("http://sharesdk.cn");
        oks.setTitleUrl(mUrl);

        // text是分享文本，所有平台都需要这个字段
        //oks.setText("我是分享文本");
        oks.setText(mTitle);

        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
       // oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        oks.setImagePath(mPicPath);
        // url仅在微信（包括好友和朋友圈）中使用
        //oks.setUrl("http://sharesdk.cn");
        oks.setUrl(mUrl);

        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("");//我是测试评论文本

        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));

        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        //oks.setSiteUrl("http://sharesdk.cn");
        oks.setSiteUrl(mUrl);

        // 启动分享GUI
        oks.show(mContext);
    }*/

    @Override
    public Object getTitleString() {
        return "详情";
    }

//    @Override
//    public void onBackPressed() {
//        super.onBackPressed();
//        if(mPush&&"0".equalsIgnoreCase(SharedPreferencesUtil.getStringValue(mContext, KeysConstans.ISOPEN))){
//            if(mWebView.canGoBack()){
//                mWebView.goBack();
//            }else {
//                Intent intent = new Intent(mContext, MainActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
//            }
//        }else{
//            if(mWebView.canGoBack()){
//                mWebView.goBack();
//            }
//        }
//    }

   public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)){
           if (mWebView.canGoBack()) {
               mWebView.goBack(); // goBack()表示返回WebView的上一页面
               return true;
           } else {
               if(mPush&&"0".equalsIgnoreCase(SharedPreferencesUtil.getStringValue(mContext, KeysConstans.ISOPEN))){
                   Intent intent = new Intent(Intent.ACTION_MAIN);
                   intent.setClass(mContext, MainActivity.class);
                   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                   startActivity(intent);
               }
              finish();
           }
       }
    return false;
  }

//    @Override
//    public void onBackPressed() {
//        super.onBackPressed();
//        if (mWebView.canGoBack()) {
//            mWebView.goBack(); // goBack()表示返回WebView的上一页面
//        } else {
////            if(mPush&&"0".equalsIgnoreCase(SharedPreferencesUtil.getStringValue(mContext, KeysConstans.ISOPEN))){
////                Log.i("fyh", "MainActivityMainActivity");
////                Intent intent = new Intent(mContext.getApplicationContext(), MainActivity.class);
////                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
////                startActivity(intent);
////            }
//            finish();
//        }
//    }

    @Override
    public int getBodyView() {
        return R.layout.play_webview_layout;
    }

    public static void launch(Activity context, String url, String title,String tag_pic) {
        Intent intent = new Intent(context, BallWebviewActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_URL, url);
        bundle.putString(BUNDLE_TITLE, title);
        bundle.putString(BUNDLE_PICURL,tag_pic);
        intent.putExtras(bundle);
        BallUtil.launch(context, intent, false, 0);
    }
}

